<template>
  <div class="page">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="movie">
      <nav class="breadcrumb">
        <router-link to="/">首页</router-link>
        / {{ movie.title }}
      </nav>
      <div class="detail-content">
        <div class="poster-section">
          <div class="poster-placeholder">
            <img :src="movie.cover" :alt="movie.title">
          </div>
          <div class="action-section">
            <div class="play-section">
              <router-link :to="`/play/${movie.id}`" class="play-btn" @click="addToWatchHistory">
                <span>▶ 播放影片</span>
              </router-link>
              <div class="source-info">
                <span>可用片源：</span>
                <span v-for="s in movie.sources" :key="s.label" class="source-tag">{{ s.label }}</span>
              </div>
            </div>

            <!-- 用户操作按钮 -->
            <div class="user-actions">
              <button
                  @click="toggleFavorite"
                  class="action-btn favorite"
                  :class="{ active: isFavorite }"
                  :title="isFavorite ? '取消收藏' : '加入收藏'"
              >
                {{ isFavorite ? '❤️ 已收藏' : '🤍 收藏' }}
              </button>

              <div class="user-rating">
                <span class="rating-label">我的评分：</span>
                <div class="rating-stars">
                  <span
                      v-for="star in 5"
                      :key="star"
                      class="star"
                      :class="{ active: star <= userRating }"
                      @click="rateMovie(star)"
                  >
                    ⭐
                  </span>
                </div>
                <span v-if="userRating > 0" class="rating-value">{{ userRating }}星</span>
                <button v-if="userRating > 0" @click="removeRating" class="remove-rating">取消</button>
              </div>
            </div>
          </div>
        </div>

        <div class="info-section">
          <h2>{{ movie.title }}</h2>
          <div class="meta">
            <span>年份：{{ movie.year }}</span> ·
            <span>评分：{{ movie.rating }}</span> ·
            <span>时长：{{ Math.round(movie.duration / 60) }} 分</span>
          </div>
          <div class="tags">
            <span class="tag" v-for="g in movie.genres" :key="g">{{ g }}</span>
          </div>
          <p class="desc">{{ movie.description }}</p>
          <div class="actors">
            <strong>演员：</strong>
            <span v-for="a in movie.actors" :key="a.id">{{ a.name }}</span>
          </div>

          <!-- 评分和评论系统 -->
          <RatingSystem :movieId="movie.id"/>
        </div>
      </div>
    </div>
    <div v-else-if="!loading" class="page">未找到影片</div>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue';
import {useRoute} from 'vue-router';
import {useMovieStore} from '../store/index';
import {useUserStore} from '../store/user';
import {movieService} from '../services/movieService';
import RatingSystem from '../components/RatingSystem.vue';
import {ElMessage} from 'element-plus';

const route = useRoute();
const store = useMovieStore();
const userStore = useUserStore();
const movie = ref(null);
const userRating = ref(0);
const loading = ref(true);

const isFavorite = computed(() => {
  return userStore.isLoggedIn &&
      userStore.favoriteMovies.some(fav => fav.movieId === movie.value?.id);
});

onMounted(async () => {
  try {
    loading.value = true;
    movie.value = await movieService.getMovie(route.params.id);

    // 初始化用户数据
    if (userStore.isLoggedIn) {
      // await userStore.initUserData();

      // 加载用户评分
      if (movie.value) {
        const rating = userStore.userRatings[movie.value.id];

        if (rating) {
          userRating.value = rating.rating;
        }
      }
    }
  } catch (error) {
    console.error('获取电影详情失败:', error);
  } finally {
    loading.value = false;
  }
});

const toggleFavorite = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录以使用收藏功能');
    return;
  }

  try {
    // 直接使用user store的方法来判断和操作，避免计算属性延迟
    const movieId = movie.value.id;
    if (isFavorite.value) {
      await userStore.removeFromFavorites(movieId);
      ElMessage.success('取消收藏成功');
    } else {
      await userStore.addToFavorites(movie.value);
      ElMessage.success('收藏成功');
    }
  } catch (error) {

  }
};

const rateMovie = async (rating) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录以进行评分');
    return;
  }

  try {
    userRating.value = rating;
    await userStore.setRating(movie.value.id, rating);
    // ElMessage.success(`已评分 ${rating} 星`)
  } catch (error) {
    // 如果接口返回code!=200，apiService会自动显示错误消息
  }
};

const removeRating = async () => {
  try {
    userRating.value = 0;
    await userStore.removeRating(movie.value.id);
    ElMessage.success('取消评分成功');
  } catch (error) {
    // 如果接口返回code!=200，apiService会自动显示错误消息
  }
};

const addToWatchHistory = () => {
  if (userStore.isLoggedIn && movie.value) {
    userStore.addToWatchHistory(movie.value);
  }
};
</script>

<style scoped>
.page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 12px;
  color: #e9eef9;
  width: 100%;
  box-sizing: border-box;
}

.breadcrumb {
  font-size: 13px;
  color: #9aa6b2;
  margin-bottom: 20px;
}

.detail-content {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

@media (max-width: 768px) {
  .detail-content {
    flex-direction: column;
  }
}

.poster-section {
  flex-shrink: 0;
  width: 300px;
}

.poster-placeholder {
  width: 100%;
  height: 450px;
  background: #1b2230;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #2a3040;
  color: #9aa6b2;
  font-size: 16px;
  overflow: hidden;
}

.poster-placeholder img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.action-section {
  margin-top: 20px;
}

.play-section {
  text-align: center;
  margin-bottom: 20px;
}

.play-btn {
  display: block;
  background: #4f8cff;
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  transition: background-color 0.2s;
}

.play-btn:hover {
  background: #3a7cff;
}

.source-info {
  margin-top: 12px;
  font-size: 13px;
  color: #9aa6b2;
}

.source-tag {
  display: inline-block;
  background: #25304a;
  color: #cfe1ff;
  padding: 2px 8px;
  border-radius: 4px;
  margin-right: 6px;
  font-size: 12px;
}

.user-actions {
  border-top: 1px solid #2a3040;
  padding-top: 20px;
}

.action-btn {
  width: 100%;
  padding: 10px;
  border: 1px solid #4f8cff;
  border-radius: 6px;
  background: transparent;
  color: #4f8cff;
  cursor: pointer;
  margin-bottom: 15px;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #4f8cff;
  color: white;
}

.action-btn.active {
  background: #4f8cff;
  color: white;
}

.action-btn.favorite.active {
  background: #e53e3e;
  border-color: #e53e3e;
}

.user-rating {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.rating-label {
  color: #9aa6b2;
  font-size: 14px;
}

.rating-stars {
  display: flex;
  gap: 2px;
}

.star {
  font-size: 18px;
  cursor: pointer;
  opacity: 0.5;
  transition: all 0.2s;
}

.star.active {
  opacity: 1;
  color: #fbbf24;
}

.star:hover {
  opacity: 1;
  transform: scale(1.1);
}

.rating-value {
  color: #fbbf24;
  font-size: 14px;
}

.remove-rating {
  padding: 2px 8px;
  border: 1px solid #e53e3e;
  border-radius: 4px;
  background: transparent;
  color: #e53e3e;
  cursor: pointer;
  font-size: 12px;
}

.remove-rating:hover {
  background: #e53e3e;
  color: white;
}

.info-section {
  flex: 1;
}

.info-section h2 {
  margin: 0 0 12px;
  font-size: 24px;
}

.meta {
  font-size: 14px;
  color: #9aa6b2;
  margin-bottom: 15px;
}

.tags .tag {
  display: inline-block;
  background: #25304a;
  color: #cfe1ff;
  padding: 3px 8px;
  border-radius: 999px;
  margin-right: 8px;
  font-size: 12px;
}

.desc {
  color: #c7d3e6;
  line-height: 1.6;
  margin-bottom: 15px;
}

.actors span {
  margin-right: 8px;
}
</style>